<?php
error_reporting("1");
ini_set('memory_limit', '1024M');
include_once("config.php");
include_once("util.php");
connect_db_mute();

function email_user_id_array() {
    $email_and_user_id_assoc = array();
    $sql = "select id, identity from local_user";
    $ret = sql_or_die($sql);

    while ($email_and_user_id = mysql_fetch_assoc($ret)) {
        $email_and_user_id_assoc[$email_and_user_id["identity"]] = $email_and_user_id["id"];
    }
    return $email_and_user_id_assoc;
}

if (isset($_FILES["mysql_table"]["tmp_name"])) {
    $file_name = explode(".", $_FILES['mysql_table']['name']);
    $table_name = $file_name[0];

    if ($_FILES["mysql_table"]["error"] > 0) {
        echo "Error: " . $_FILES["mysql_table"]["error"];
        return;
    }
    $table_content = file_get_contents($_FILES["mysql_table"]["tmp_name"]);
    
    if ($file_name[1] == 'csv') {
        $table_content = array_map("trim", explode("\n", $table_content));

        //$rows = array();
        foreach ($table_content as $key => $value) {
            $value = trim($value);
            if (strlen($value) == 0)
                continue;
            if ($key == 0) {
                $title = $value;
                if (strpos("$value", "user_id"))
                    $email_and_user_id_assoc = email_user_id_array();
            }

            else if (isset($email_and_user_id_assoc)) {
                $value = str_replace('"', '', $value);
                $value_explode = array_map("trim", explode(",", $value));
                $email = $value_explode[0];
                $insert_data = sprintf('%s, %s', $email_and_user_id_assoc[$email], $value_explode[1]);
                //array_push($rows, $insert_data);
                $sql = "insert ignore into $table_name ($title) values ($insert_data)";
                echo $sql;
                return;
                sql_or_die($sql);
            }

            else if (!isset($email_and_user_id_assoc)) {
                $sql = "insert ignore into $table_name ($title) values ($value)";
                echo $sql;
                sql_or_die($sql);
            }
        }
    }

    if ($file_name[1] == 'json') {
        //var_dump(json_decode($table_content, true));
        //print 'json_encode';
        //return;
        $table_content = explode("{", $table_content);
        array_shift($table_content);
        $email_and_user_id_assoc = email_user_id_array();
        foreach ($table_content as $each_content) {
            $each_content = str_replace('}', '', $each_content);
            $each_content = explode(",", $each_content);
            array_pop($each_content);
            foreach ($each_content as $resolved_each_content) {
                $resolved_each_content = str_replace('"', '', $resolved_each_content);
                $resolved_each_content = explode(":", $resolved_each_content);
                $title .= ",$resolved_each_content[0]";
                if (strpos($resolved_each_content[0], "email")) {
                    $email = $resolved_each_content[1];
                    $email = trim($email);
                    $content = $email_and_user_id_assoc["$email"];
                }
                else
                    $content = $resolved_each_content[1];
                $content_string .= sprintf(',"%s"', trim($content));
                $content_string = trim($content_string, ',');
                $title = str_replace('user_email', 'user_id', $title);
                $title = trim($title, ',');
                if (strpos($title, 'value')) {
                    $sql = "insert ignore into $file_name[0] ($title) values ($content_string)";
                    echo $sql;
                    echo '<br />';
                    sql_or_die($sql);
                    unset($title);
                    unset($content_string);
                }
            }
        }
    }
}
?>

<!DOCUMENTTYPE html>
<html> 
<head>
<title>import data to database</title>
</head>
<body>
    <center>
        <form action="../cgi/import_table.py" method="post" enctype="multipart/form-data">
          <input type="file" name="mysql_table" size="50" id="file-input">
          <input type="submit" value="submit">
        </form>
    </center>
</body>
</html>
